<template>
  <div class="navbar">
    <button @click="router.go(-1)">返回上一级</button>
    <div>聊天页面</div>
    <button @click="addNewMessage">模拟接受新消息</button>
  </div>
  <hr />
  <div class="chatRoom">
    <div
      v-for="(item, index) in msgList"
      :key="index"
      :class="[
        'chatItem',
        JSON.parse(item.msgFrom).userId === myId
          ? 'chatItemRight'
          : 'chatItemLeft',
      ]"
    >
      <div>
        <div
          v-if="item.msgType === 'text'"
          :class="[
            'text',
            JSON.parse(item.msgFrom).userId === myId ? 'textRight' : 'textLeft',
          ]"
        >
          {{ item.message }}
        </div>
        <div v-if="item.msgType === 'picture'" @click="downFile(item.fileName)">
          <img
            :src="item.filePath"
            alt=""
            class="chatImg"
            @error="errorImg(item)"
          />
          <!-- <img src="http://192.168.10.7:5000/uploads/chat_emotion_0.png" alt=""> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from "vue-router";
import { onMounted, ref } from "vue";
import { getMessagesByPage, insertMessage } from "@/db/model/message";
import { getDownload } from "@/api/upload";
import fs from "fs";

onMounted(() => {
  searchMsg();
});
const onlineUrl = "http://192.168.0.106:5000/uploads/";
const myId = 1;
const router = useRouter();
const searchData = {
  page: 1,
  pageSize: 10,
};
const msgList = ref([]);
const searchMsg = () => {
  getMessagesByPage(searchData).then((res) => {
    console.log(res);
    msgList.value = res.reverse();
  });
};
const errorImg = (e) => {
  // 图片加载失败时，替换为默认图片
  e.filePath = onlineUrl + e.fileName;
  downFile(e.fileName)
    .then(() => {
      console.log("图片下载成功");
    })
    .catch(() => {
      console.log("图片下载失败");
    });
};
const downFile = (fileName) => {
  return new Promise((resolve, reject) => {
    getDownload({ file: fileName }).then((res) => {
      // res 是Blob对象，可以直接下载，用FileReader可以转换为ArrayBuffer对象再转为Buffer对象保存到本地
      const reader = new FileReader();
      reader.onload = function (event) {
        // event.target.result 是ArrayBuffer
        const arrayBuffer = event.target.result;
        const buffer = Buffer.from(arrayBuffer);
        // 处理arrayBuffer...
        fs.writeFile(`file/${fileName}`, buffer, (err) => {
          if (err) {
            reject(err);
          } else {
            resolve("success");
          }
        });
      };
      reader.readAsArrayBuffer(res);
    });
  });
};
const addNewMessage = async () => {
  const msg = {
    msgFrom: {
      userId: 1,
      userName: "张三",
    },
    msgTo: {
      userId: 2,
      userName: "李四",
    },
    msgType: "picture",
    message: "",
    fileName: "oa.png",
    filePath: "file/oa.png",
    timeStamp: new Date().getTime(),
  };
  msg.msgFrom = JSON.stringify(msg.msgFrom);
  msg.msgTo = JSON.stringify(msg.msgTo);
  await insertMessage(msg);
};
</script>

<style scoped lang="scss">
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chatRoom {
  width: 80%;
  height: 400px;
  margin: 0 auto;
  border: 2px solid #ccc;
  overflow-y: auto;
  .chatItem {
    margin: 20px 15px;
    .text {
      font-size: 14px;
      max-width: 100px;
      padding: 10px;
      border-radius: 5px;
      word-break: break-all;
    }
    .chatImg {
      width: 100px;
      height: 100px;
      object-fit: cover;
    }
  }
  .chatItemLeft {
    display: flex;
    justify-content: flex-start;
  }
  .chatItemRight {
    display: flex;
    justify-content: flex-end;
  }
  .textLeft {
    background-color: #e8e8e9;
  }
  .textRight {
    background-color: #c9e7ff;
  }
}
</style>